package com.jaya.budan.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.google.gson.Gson;
import com.jaya.budan.R;
import com.jaya.budan.base.BaseActivity;
import com.jaya.budan.connect.RequestConnect;
import com.jaya.budan.utils.CountDownTimer;
import com.jaya.budan.utils.ToolUtils;
import com.jaya.budan.utils.VolleyUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

public class Register2_Activity extends BaseActivity implements View.OnClickListener {

    private EditText et_forget_1, et_forget_2, et_forget_3, et_forget_4, et_forget_5, et_forget_6;
    private Button btn_register;
    private String username, password, rpassword;
    private RelativeLayout back;
    private TextView tv_register2_mobile, tv_register2_rsms, tv_register2_agree;
    private CheckBox cb_register2;
    private String str_yzm;
    private boolean b = true;
    CountDownTimer timer = new CountDownTimer(60000, 1000) {

        @Override
        public void onTick(long millisUntilFinished) {
            tv_register2_rsms.setText(millisUntilFinished / 1000 + "秒后重新发送验证码");
        }

        @Override
        public void onFinish() {
            tv_register2_rsms.setText("重新获取验证码");
        }
    };
    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register2);
        Intent intent = getIntent();
        username = intent.getStringExtra("username");
        password = intent.getStringExtra("password");
        rpassword = intent.getStringExtra("rpassword");
        tv_register2_mobile = findViewById(R.id.tv_register2_mobile);
        tv_register2_rsms = findViewById(R.id.tv_register2_rsms);
        tv_register2_agree = findViewById(R.id.tv_register2_agree);
        cb_register2 = findViewById(R.id.cb_register2);
        et_forget_1 = findViewById(R.id.et_forget_1);
        et_forget_2 = findViewById(R.id.et_forget_2);
        et_forget_3 = findViewById(R.id.et_forget_3);
        et_forget_4 = findViewById(R.id.et_forget_4);
        et_forget_5 = findViewById(R.id.et_forget_5);
        et_forget_6 = findViewById(R.id.et_forget_6);
        btn_register = findViewById(R.id.btn_register);
        back = findViewById(R.id.back);
        tv_register2_mobile.setText("您的手机" + ToolUtils.settingphone(username + ""));
        btn_register.setOnClickListener(this);
        back.setOnClickListener(this);
        cb_register2.setOnClickListener(this);
        JSONObject object = new JSONObject();
        try {
            object.put("username", username);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        postData_sms(object);//获取验证码
        et_forget_1.setFocusable(true);
        et_forget_2.setFocusable(true);
        et_forget_3.setFocusable(true);
        et_forget_4.setFocusable(true);
        et_forget_5.setFocusable(true);
        et_forget_6.setFocusable(true);
        et_forget_1.addTextChangedListener(textWatcher);
        et_forget_2.addTextChangedListener(textWatcher);
        et_forget_3.addTextChangedListener(textWatcher);
        et_forget_4.addTextChangedListener(textWatcher);
        et_forget_5.addTextChangedListener(textWatcher);
        et_forget_6.addTextChangedListener(textWatcher);
        SpannableString spanString = new SpannableString("《用户协议》");
        spanString.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                //点击的响应事件
                ToolUtils.showToast(Register2_Activity.this, "用户协议");
            }
        }, 0, spanString.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanString.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")), 0, spanString.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        SpannableString spanString2 = new SpannableString("《隐私条款》");
        spanString2.setSpan(new ClickableSpan() {
            @Override
            public void onClick(View view) {
                //点击的响应事件
                ToolUtils.showToast(Register2_Activity.this, "隐私条款");
            }
        }, 0, spanString2.length(), Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
        spanString2.setSpan(new ForegroundColorSpan(Color.parseColor("#007AFF")), 0, spanString2.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        tv_register2_agree.setText("注册代表我同意不单");
        tv_register2_agree.append(spanString);
        tv_register2_agree.append("和");
        tv_register2_agree.append(spanString2);
        tv_register2_agree.append(", 且承诺，我已满十八周岁，并清楚了解不单平台禁止十八周岁以下未成年注册及使用的各项规定。");
        tv_register2_agree.setMovementMethod(LinkMovementMethod.getInstance());//开始响应点击事件
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if(s.length()==1){
                if(et_forget_1.isFocusable()){
                    et_forget_2.setFocusable(true);
                    et_forget_2.setFocusableInTouchMode(true);
                }else if(et_forget_2.isFocusable()){
                    et_forget_3.setFocusable(true);
                    et_forget_3.setFocusableInTouchMode(true);
                }else if(et_forget_3.isFocusable()){
                    et_forget_4.setFocusable(true);
                    et_forget_4.setFocusableInTouchMode(true);
                }else if(et_forget_4.isFocusable()){
                    et_forget_5.setFocusable(true);
                    et_forget_5.setFocusableInTouchMode(true);
                }else if(et_forget_5.isFocusable()){
                    et_forget_6.setFocusable(true);
                    et_forget_6.setFocusableInTouchMode(true);
                }
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.toString().length() == 1) {
                if (et_forget_1.isFocused()) {
                    et_forget_1.setFocusable(false);
                    et_forget_2.requestFocus();
                }else if (et_forget_2.isFocused()) {
                    et_forget_2.setFocusable(false);
                    et_forget_3.requestFocus();
                }else if(et_forget_3.isFocused()){
                    et_forget_3.setFocusable(false);
                    et_forget_4.requestFocus();
                }else if(et_forget_4.isFocused()){
                    et_forget_4.setFocusable(false);
                    et_forget_5.requestFocus();
                }else if(et_forget_5.isFocused()){
                    et_forget_5.setFocusable(false);
                    et_forget_6.requestFocus();
                }else if(et_forget_6.isFocused()){
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(et_forget_6.getWindowToken(), 0);
                    str_yzm = et_forget_1.getText().toString().trim() + et_forget_2.getText().toString().trim() + et_forget_3.getText().toString().trim()
                            + et_forget_4.getText().toString().trim() + et_forget_5.getText().toString().trim() + et_forget_6.getText().toString().trim();
                }
            }
        }
    };

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_register:
                JSONObject object = new JSONObject();
                try {
                    object.put("username", username);
                    object.put("password", password);
                    object.put("r_password", rpassword);
                    object.put("sms", str_yzm);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                postData(object);//注册
                break;
            case R.id.cb_register2:
                if (cb_register2.isEnabled()){
                    cb_register2.setEnabled(true);
                    cb_register2.setBackgroundResource(R.mipmap.iv_duihao_yellow);
                    btn_register.setEnabled(true);
                } else {
                    cb_register2.setEnabled(false);
                    cb_register2.setBackgroundResource(R.mipmap.iv_duihao_no);
                    btn_register.setEnabled(false);
                }
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    /**
     * 网络请求
     * @param object
     */
    private void postData(JSONObject object) {
        Log.d("register", object.toString());
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.register_Url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("register", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
                        JSONObject info = jsonObject.getJSONObject("info");
                        String access_token = info.getString("access_token");
                        Intent intent = new Intent(Register2_Activity.this, Register3_Activity.class);//已注册，自动跳转至下一步
                        intent.putExtra("access_token", access_token);
                        startActivity(intent);
                        finish();
                    } else if (code == 500){ //账号已经存在，请直接登录
                        ToolUtils.showToast(Register2_Activity.this, message);
                        Intent intent = new Intent(Register2_Activity.this, LoginActivity.class);
                        startActivity(intent);
                    } else {
                        ToolUtils.showToast(Register2_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Register2_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    /**
     * 网络请求
     * @param object
     */
    private void postData_sms(JSONObject object) {
        JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, RequestConnect.register_GetSMS_Url, object, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject jsonObject) {
                Log.d("register_sms", jsonObject.toString());
                try {
                    int code = jsonObject.optInt("code");
                    int status = jsonObject.optInt("status");
                    String message = jsonObject.getString("message");
                    if (code == 0) {
                        Gson gson = new Gson();
//                        JSONObject info = jsonObject.getJSONObject("info");
//                        data = info.getInt("data");
                        timer.start();//启用倒计时
                        ToolUtils.showToast(Register2_Activity.this, message);
                    } else {
                        ToolUtils.showToast(Register2_Activity.this, message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                ToolUtils.showToast(Register2_Activity.this, "网络请求失败，请稍后重试~");
            }
        });
        request.setTag(this);
        VolleyUtil.getQueue(this).add(request);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        timer.cancel();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_DEL) {
            if(et_forget_6.isFocused()){
                if (!et_forget_6.getText().toString().equals("")) {
                    et_forget_6.getText().clear();
                    et_forget_6.requestFocus();
                    b = false;
                } else if (!b) {
                    et_forget_6.clearFocus();
                    et_forget_6.setFocusable(false);
                    et_forget_5.setFocusableInTouchMode(true);
                    et_forget_5.getText().clear();
                    et_forget_5.requestFocus();
                    b = true;
                } else {
                    et_forget_6.getText().clear();
                    et_forget_6.requestFocus();
                    b = false;
                }
            } else if (et_forget_5.isFocused()) {
                et_forget_5.clearFocus();
                et_forget_5.setFocusable(false);
                et_forget_4.setFocusableInTouchMode(true);
                et_forget_4.getText().clear();
                et_forget_4.requestFocus();
            } else if (et_forget_4.isFocused()) {
                et_forget_4.clearFocus();
                et_forget_4.setFocusable(false);
                et_forget_3.setFocusableInTouchMode(true);
                et_forget_3.getText().clear();
                et_forget_3.requestFocus();
            } else if (et_forget_3.isFocused()) {
                et_forget_3.clearFocus();
                et_forget_3.setFocusable(false);
                et_forget_2.setFocusableInTouchMode(true);
                et_forget_2.getText().clear();
                et_forget_2.requestFocus();
            } else if (et_forget_2.isFocused()) {
                et_forget_2.clearFocus();
                et_forget_2.setFocusable(false);
                et_forget_1.setFocusableInTouchMode(true);
                et_forget_1.getText().clear();
                et_forget_1.requestFocus();
            }
        }
        if(keyCode == KeyEvent.KEYCODE_BACK){
            this.finish();
        }
        return false;
    }
}
